package com.xjc.market.acct.biz;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xjc.infra.base.BaseBiz;
import com.xjc.infra.entity.ExecuteState;
import com.xjc.infra.entity.SessionContext;
import com.xjc.infra.exception.IFSException;
import com.xjc.infra.util.ClassUtil;
import com.xjc.market.acct.entity.UserObjectEntity;
import com.xjc.market.acct.entity.table.AcOperator;
import com.xjc.market.frame.entity.Constant;
import com.xjc.market.frame.util.FrameUtil;

/**
 * 登录biz
 * @author liangcz
 * @Date   2017年9月20日 下午1:40:24
 * @version 1.0
 */
@Service
public class LoginBiz extends BaseBiz{
	@Autowired
	AcOperatorBiz acOperatorBiz;
	/**
	 * 登录
	 * @author liangcz
	 * @date   2017年9月20日 下午1:43:41
	 * @return void
	 */
	public ExecuteState login(SessionContext sessionContext,HttpSession session,AcOperator acOperator){
		ExecuteState state = new ExecuteState();
		try {
			/* 1、判断用户存不存在
			 * 2、校验用户密码
			 * 3、用户数据存入session
			 * */
			String userid = acOperator.getUserid();
			String pwd = acOperator.getPwd();
			String phone = acOperator.getPhone();
			String pwdSaltMd5Str = FrameUtil.md5AddSalt(pwd, userid);
			// String pwdSaltMd5Str = Md5Crypt.md5Crypt((userid + pwd).getBytes());
			// String pwdSaltMd5Str = Md5Crypt.md5Crypt(pwd.getBytes(), userid);
			List<AcOperator> acOperatorList = acOperatorBiz.inquiryAcOperatorList(userid,phone);
			if(acOperatorList == null || acOperatorList.size() == 0){
				throw new IFSException(null, "LoginBiz.login.01", "用户不存在");
			}
			if(acOperatorList.size() != 1){
				throw new IFSException(null, "LoginBiz.login.02", "系统错误，存在多个操作员");
			}
			AcOperator acOperatorSelect = acOperatorList.get(0);
			if(acOperatorSelect.getPwd().equalsIgnoreCase(pwdSaltMd5Str) == false){
				throw new IFSException(null, "LoginBiz.login.03", "密码错误");
			}
			acOperatorSelect.setLastlogin(new Date());
			acOperatorBiz.updateAll(acOperatorSelect);
			state.setSuccess(true);
			UserObjectEntity userObjectEntity = new UserObjectEntity();
			userObjectEntity.setAcOperator(acOperatorSelect);
			session.setAttribute(Constant.USER_SESSION_ID, userObjectEntity);
		} catch (IFSException e) {
			state.setErrorCode(e.getErrorCode());
			state.setSuccess(false);
			state.setMessage(e.getMessage());
			loggerUtil.logError(acOperator, sessionContext, ClassUtil.getAbsoluteMethodName(Thread.currentThread().getStackTrace()),e);
		} catch (Exception e) {
			state.setSuccess(false);
			state.setErrorCode("LoginBiz.login.99");
			state.setMessage("登录失败");
			loggerUtil.logError(acOperator, sessionContext, ClassUtil.getAbsoluteMethodName(Thread.currentThread().getStackTrace()), new IFSException(e, "LoginBiz.login.99", "登录失败"));
		}
		return state;
	}
}
